package com.zxl.demo;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/31 13:52
 * 图片验证码
 */
@WebServlet(name = "ImageServlet",value = "/ImageServlet")
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置浏览器2秒刷新
        resp.setHeader("refresh","3");
        //创建图片
        BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //创建笔
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        //设置背景颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0,0,80,20);
        //写数据
        graphics.setColor(Color.RED);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(new Random().nextInt(99999)+"",0,20);
        //设置浏览器用图片打开
        resp.setContentType("image/jpg");
        //不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");
        //写入图片
        ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
